<?php
/**
 *
 * Prado Portal - Simple benchmarking.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: PortalBM.php 289 2008-11-14 05:34:40Z steen.rabol@gmail.com $
 * @package Pradoportal.Common
 *
 */

class PortalBM
{
	// Benchmark timestamps
	private static $marks;

	/**
	 * Set a benchmark start point.
	 *
	 * @param   string  benchmark name
	 * @return  void
	 */
	public static function start($name)
	{
		if ( ! isset(self::$marks[$name]))
		{
			self::$marks[$name] = array
			(
				'start'        => microtime(true),
				'stop'         => false,
				'memory_start' => memory_get_usage(true),
				'memory_stop'  => false
			);
		}
	}

	/**
	 * Set a benchmark stop point.
	 *
	 * @param   string  benchmark name
	 * @return  void
	 */
	public static function stop($name)
	{
		if (isset(self::$marks[$name]) && self::$marks[$name]['stop'] === false)
		{
			self::$marks[$name]['stop'] = microtime(true);
			self::$marks[$name]['memory_stop'] = memory_get_usage(true);
		}
	}

	/**
	 * Get the elapsed time between a start and stop.
	 *
	 * @param   string   benchmark name, TRUE for all
	 * @param   integer  number of decimal places to count to
	 * @return  array
	 */
	public static function get($name, $decimals = 4)
	{
		if ($name === TRUE)
		{
			$times = array();
			$names = array_keys(self::$marks);

			foreach ($names as $name)
			{
				// Get each mark recursively
				$times[$name] = self::get($name, $decimals);
			}

			// Return the array
			return $times;
		}

		if ( ! isset(self::$marks[$name]))
			return FALSE;

		if (self::$marks[$name]['stop'] === FALSE)
		{
			// Stop the benchmark to prevent mis-matched results
			self::stop($name);
		}

		// Return a string version of the time between the start and stop points
		// Properly reading a float requires using number_format or sprintf
		return array
		(
			'time'   => number_format(self::$marks[$name]['stop'] - self::$marks[$name]['start'], $decimals),
			'memory' => (self::$marks[$name]['memory_stop'] - self::$marks[$name]['memory_start'])
		);
	}

	public static function ViewBmResult($bmpoint)
	{
		$result	= PortalBM::get($bmpoint);
		echo "BM Point: $bmpoint - Time: " . $result['time'] . " memory: " . ($result['memory'] / 1024) . "kb<br>";
	}

	public static function ViewAllBmResults()
	{
		$names = array_keys(self::$marks);
		foreach ($names as $name)
		{
			self::ViewBmResult($name);
		}

	}
}
